import React, { useState, useEffect, useRef } from 'react';
import { Form, Modal, Space, Table, message, Button } from 'antd';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { getMyOrganizeListPage,saveOrUpdateUserOrganize,delUserOrganize } from '../service';
import SelectOneOrganize from '../../../system/organize/components/SelectOneOrganize';

export type mangeOrganizeFormProps = {
    onCancel: (flag?: boolean, formVals?: any) => void;
    onSubmit: (values: any) => Promise<void>;
    manageOrganizeModalVisible: boolean;
    values: any;
};

const handleAdd = async (fields: any) => {
    const hide = message.loading('正在添加');
    try {
        await saveOrUpdateUserOrganize(fields);
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
    }
};

const handleRemove = async (del_id: any) => {
    const hide = message.loading('正在删除');
    try {
      await delUserOrganize(del_id);
      hide();
      message.success('删除成功，即将刷新');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  
const mangeOrganizeForm: React.FC<mangeOrganizeFormProps> = (props) => {
    const formRef = useRef<any>();
    /** 新建窗口的弹窗 */
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);

    const [data, setData] = useState<any>();
    const [pagination, setPagination] = useState<any>({ current: 1, pageSize: 10 });

    const [oneOrganizeModalVisible, handleOneOrganizeModalVisible] = useState<boolean>(false);
    const [oneOrganizeData, handleOneOrganizeData] = useState<any>();

    useEffect(() => {
        findOrganizeList();
        
    }, [props.manageOrganizeModalVisible]);

    const handleCancel = () => {
        props.onCancel()
    }

    const findOrganizeList = async () => {
        const hide = message.loading('正在查询');
        try {
            await getMyOrganizeListPage({ user_id: props.values.id, }).then(res => {
                setData(res.data.rows)
            })
            hide();
            // message.success('数据查询成功');
            return true;
        } catch (error) {
            hide();
            // message.error('数据查询失败');
            return false;
        }
    };

    const columns = [
        {
            title: '组织类型',
            key: 'type',
            dataIndex: 'type',
            render: (type: any) => {
                if (type == "0") {
                    return "主组织"
                } else if (type == "1") {
                    return "兼职组织"
                } else {
                    return "未知"
                }
            },
        },
        {
            title: '组织名称',
            dataIndex: 'organize_name',
            key: 'organize_name'
        },
        {
            title: '职务',
            dataIndex: 'position',
            key: 'position',
            render: (position: any) => {
                if (position == "" || position == null) {
                    return "未指定";
                } else {
                    return position;
                }
            },
        },
        {
            title: '排序',
            dataIndex: 'order_by',
            key: 'order_by',
        },

        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    <Button type="primary" size='small' key="config"
                        onClick={() => {
                            handleModalVisible(true)
                            let type_name = '主组织';
                            if(record.type!='0'){
                                type_name = '兼职组织';
                            }
                            formRef.current.setFieldsValue({...record,type_name:type_name});
                        }}>
                        编辑
                    </Button>
                    <Button type="primary" size='small' danger onClick={async () => {
                        Modal.confirm({
                            title: '删除任务',
                            content: '确定删除该任务吗？',
                            okText: '确认',
                            cancelText: '取消',
                            onOk: () => {
                                handleRemove(record.id);
                                findOrganizeList();
                            },
                        });
                    }}>
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    const handleTableChange = (pagination, filters, sorter) => {
        console.log('--------------')
        console.log(pagination)
    };

    return (
        <Modal
            width={900}
            title='组织管理'
            visible={props.manageOrganizeModalVisible}
            destroyOnClose
            onCancel={handleCancel}
        >
            <Button
                type="dashed"
                style={{ width: '100%', marginBottom: 8 }}
                onClick={() => {
                    handleModalVisible(true)
                    formRef.current.setFieldsValue({
                        id: "",
                        type: "1",
                        type_name: "兼职组织",
                        organize_id: "",
                        organize_name: "",
                        position: "",
                        order_by: "",
                        remark: ""
                    });
                }}
            >
                <PlusOutlined />
              添加
            </Button>
            <Table columns={columns}
                dataSource={data}
                bordered
                pagination={pagination}
                onChange={handleTableChange}
            />
            <ModalForm
                title='添加用户组织'
                width="600px"
                formRef={formRef}
                visible={createModalVisible}
                onVisibleChange={handleModalVisible}
                onFinish={async (value) => {
                    const success = await handleAdd({...value,user_id:props.values.id} as any);
                    if (success) {
                        handleModalVisible(false);
                        findOrganizeList();
                    }
                }}
            >
                 <ProFormText
                    width="xl"
                    name="id"
                    hidden
                />
                 <ProFormText
                    width="xl"
                    name="type"
                    hidden
                />
                <ProFormText
                    label='组织类型'
                    width="xl"
                    name="type_name"
                    disabled
                    placeholder="请输入组织类型"
                />
                <ProFormText
                    width="xl"
                    name="organize_id"
                    placeholder="请选择组织"
                    hidden
                />
                <ProFormText
                    label='选择组织'
                    rules={[
                        {
                            required: true,
                            message: '请选择组织',
                        },
                    ]}
                    width="xl"
                    name="organize_name"
                    placeholder="请选择组织"
                    disabled
                />
                <Button type="primary" size="small" onClick={() => {
                    handleOneOrganizeModalVisible(true);
                }}>选择</Button>
                <ProFormText
                    label='职务'
                    width="xl"
                    name="position"
                    placeholder="请输入职务"
                />
                <ProFormText
                    label='排序'
                    width="xl"
                    name="order_by"
                    placeholder="请输入排序"
                />
                <ProFormTextArea width="xl" name="remark" label='备注'
                    placeholder="请输入备注"
                />
            </ModalForm>
            <SelectOneOrganize
                onSubmit={async (value: any) => {
                    let organize_id = value.map((item: any) => item.id);
                    let organize_name = value.map((item: any) => item.name);
                    formRef.current.setFieldsValue({
                        organize_id: organize_id.join(','),
                        organize_name: organize_name.join(',')
                    });
                    handleOneOrganizeData(value);
                    handleOneOrganizeModalVisible(false);
                }}
                onCancel={() => {
                    handleOneOrganizeModalVisible(false);
                }}
                oneOrganizeModalVisible={oneOrganizeModalVisible}
                values={oneOrganizeData}
            />
        </Modal >
    );
};

export default mangeOrganizeForm;
